package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wq.common.R;
import com.wq.dto.DishDto;
import com.wq.dto.SetmealDto;
import com.wq.entity.Category;
import com.wq.entity.Dish;
import com.wq.entity.DishFlavor;
import com.wq.entity.Setmeal;
import com.wq.service.CategoryService;
import com.wq.service.DishFlavorService;
import com.wq.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-22 11:09
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    DishService dishService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        String dishKey = "dish_" + dishDto.getCategoryId() + "_*";
        final Set keys = redisTemplate.keys(dishKey);
        redisTemplate.delete(keys);
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        /**
         * 根据分页信息查询菜品信息
         */
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        final Page<Dish> dishPage = dishService.page(pageInfo, lqw);

        /**
         * Dish 中没有 categoryName 字段（前台需要），只有 categoryId
         * 因此需要根据 categoryId 从 category 表 中查询出 categoryName
         * 并将 categoryName 赋值给 DishDto 数据传输对象
         */
        Page<DishDto> dishDtoPage = new Page<>(); // 不能是 null
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> dishList = dishPage.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            final Long categoryId = item.getCategoryId();
            final Category category = categoryService.getById(categoryId);
            final String categoryName = category.getName();
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            dto.setCategoryName(categoryName);
            return dto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> echo(@PathVariable Long id) {
        DishDto dishDto = dishService.getDishDtoById(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        /**
         * 后台修改菜品数据后需要清理缓存
         * 可以全部清理，也可以精确清理
         *
         */
//        全部清理
//        final Set keys = redisTemplate.keys("dish*");
//        redisTemplate.delete(keys);

//        精确清理
        String dishKey = "dish_" + dishDto.getCategoryId() + "_*";
        final Set keys = redisTemplate.keys(dishKey);
        redisTemplate.delete(keys);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    //    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Dish::getCategoryId,dish.getCategoryId());
//        lqw.eq(Dish::getStatus,1);
//        final List<Dish> dishList = dishService.list(lqw);
//        return R.success(dishList);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        List<DishDto> dishDtoList = null;
        String dishKey = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(dishKey);
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, dish.getCategoryId());
        lqw.eq(Dish::getStatus, 1);
        final List<Dish> dishList = dishService.list(lqw);
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            final Long dishID = item.getId();
            LambdaQueryWrapper<DishFlavor> lqwFlavor = new LambdaQueryWrapper<>();
            lqwFlavor.eq(DishFlavor::getDishId, dishID);
            final List<DishFlavor> dishFlavors = dishFlavorService.list(lqwFlavor);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(dishKey, dishDtoList, 60l, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
